package cn.com.ttblog.ssmbootstrap_table.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InjectionAttackFilter implements Filter {

	private static final String X_FRAME_VALUE = "SAMEORIGIN";
	private static final String X_FRAME_HEADER = "X-FRAME-OPTIONS";
	public static final String FILTER_XSS_PARAM_NAME = "filter_xss";
	public static final String FILTER_SQL_INJECTION_PARAM_NAME = "filter_sql_injection";
	public static final String CLICK_JACKING_HEADER = "click_jacking_header";

	boolean filterXSS = true;
	boolean filterSQL = true;
	boolean clickJacking = true;

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
	        throws IOException, ServletException {
		//处理的是请求,将请求中的部分参数进行替换。
		InjectionAttackWrapper wrapper = new InjectionAttackWrapper((HttpServletRequest) servletRequest, filterXSS,
		        filterSQL);
		//处理的是响应，在响应中添加禁止Frame的标签。
		filterClickJack(servletResponse);
		//交给过滤链进行过滤
		filterChain.doFilter(wrapper, servletResponse);
	}

	/**
	 * 防止网页被Frame<br>
	 * 浅析点击劫持（click jacking）<br>
	 * 具体信息参见：http://www.css88.com/archives/5141<br>
	 * http://www.cnetsec.com/article/14290.html<br>
	 * @Title: filterClickJack 
	 * @Description: TODO(这里用一句话描述这个方法的作用) 
	 * @param  @param servletResponse 
	 * @return void    返回类型 
	 * @throws
	 */
	private void filterClickJack(ServletResponse servletResponse) {
		if (clickJacking) {
			if (servletResponse instanceof HttpServletResponse) {
				HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
				if (!httpServletResponse.containsHeader(X_FRAME_HEADER)) {
					httpServletResponse.addHeader(X_FRAME_HEADER, X_FRAME_VALUE);
				}
			}
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		String filterXSSParam = config.getInitParameter(FILTER_XSS_PARAM_NAME);
		String filterSQLParam = config.getInitParameter(FILTER_SQL_INJECTION_PARAM_NAME);
		String clickJackingParam = config.getInitParameter(CLICK_JACKING_HEADER);
		filterXSS = new Boolean(filterXSSParam);
		filterSQL = new Boolean(filterSQLParam);
		clickJacking = new Boolean(clickJackingParam);
	}

}
